<template>
  <a-select
    v-model:value="state.value"
    label-in-value
    :mode="mode || ''"
    placeholder="Select users"
    :max-tag-count="maxTagCount"
    style="width: 100%"
    :filter-option="false"
    :field-names="{ label: label, value: value }"
    :not-found-content="state.fetching ? undefined : null"
    :options="state.data"
    @search="fetchUser"
    @focus="handelFocus"
    @dropdownVisibleChange="dropdownVisibleChange"
  >
    <template v-if="state.fetching" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>
<script lang="ts" setup>
  import { reactive, watch, withDefaults } from "vue"
  import { debounce } from "lodash-es"
  import { country } from "@/api/index"
  import { dataTypes } from "@/utils/index"
  import type { selectAsyncInstance } from "./instance"
  const props = withDefaults(defineProps<selectAsyncInstance>(), {
    label: "label",
    value: "value",
    mode: "",
    maxTagCount: 2,
  })

  let lastFetchId = 0

  const state = reactive({
    data: [],
    value: [],
    fetching: false,
  })

  const fetchUser = debounce((value: string) => {
    lastFetchId += 1
    state.data = []
    const isFunction = dataTypes().isFunction(props.requestOptions)
    if (!isFunction) {
      return
    }
    props
      .requestOptions(value)
      .then((res: any) => {
        console.log("res", res)
        state.data = res
        state.fetching = false
      })
      .catch(() => {
        state.fetching = true
      })
  }, 300)

  const handelFocus = () => {
    !state.data.length && fetchUser()
  }

  const dropdownVisibleChange = (open) => {
    // !open && (state.data = []);
  }

  watch(state.value, () => {
    state.data = []
    state.fetching = false
  })
</script>
